package com.landiao.common.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.landiao.common.SpringUtils;
import com.landiao.common.pojo.ReturnSms;
import com.landiao.common.pojo.SmsConfig;
import com.thoughtworks.xstream.XStream;

/**
 * 请求http地址
 *
 */
public class HttpClientUtil {

	private static SmsConfig smsConfig = SpringUtils.getBean(SmsConfig.class);
	
	private static final Logger log = LoggerFactory.getLogger(HttpClientUtil.class);

	private static XStream xStream;
	
	static{
		xStream = new XStream();
		xStream.processAnnotations(ReturnSms.class);
	}
	
	public static boolean postSmsMessage(String phone,String message){
		HttpURLConnection connection=null;
		BufferedReader bufferedReader = null;
		try {
			//action=send&userid=12&account=账号&password=密码&mobile=15023239810,13527576163&content=内容&sendTime=&extno=
			String mess = smsConfig.getActionSend()+"&mobile="+phone+"&content="+message;
			URL url = new URL(smsConfig.getSmsUrl());
			connection = (HttpURLConnection) url.openConnection();
			connection.setRequestMethod("POST");
			connection.setConnectTimeout(6000);//设置连接超时
			connection.setDoOutput(true);// 是否输入参数
			connection.setDoInput(true);// 是否输入参数
			connection.getOutputStream().write(mess.getBytes("UTF-8"));// 输入参数
			InputStream inputStream = connection.getInputStream();
//			//对应的字符编码转换
//			bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
//			String str = null;
//			StringBuffer sb = new StringBuffer();
//			while((str = bufferedReader.readLine()) != null) {
//				sb.append(str);
//			}
//			String data = sb.toString();
//			log.debug("短信请求返回信息："+data);
			ReturnSms returnSms = (ReturnSms)xStream.fromXML(inputStream);
			log.debug("短信请求返回信息：{}",returnSms);
			if(returnSms.getReturnstatus().equals("Success"))
				return true;
			else
				return false;
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			try{
				if (bufferedReader != null){
					bufferedReader.close();
				}
				if(connection != null) {
					connection.disconnect();
				} 
			}catch (IOException ex){
				ex.printStackTrace();
			}
		}
		return false;
	}
	
	/**
	 * 向指定URL发送GET方法的请求
	 * 
	 * @param url
	 *            发送请求的URL
	 * @param params
	 *            请求参数，请求参数应该是name1=value1&name2=value2的形式。
	 * @return URL所代表远程资源的响应
	 */
	public static String sendGet(String url, String params)
	{
		return sendGet(url, params, null);
	}

	/**
	 * 向指定URL发送GET方法的请求
	 * 
	 * @param url
	 *            发送请求的URL
	 * @param params
	 *            请求参数，请求参数应该是name1=value1&name2=value2的形式。
	 * @param headerMap
	 *            http头
	 * @return URL所代表远程资源的响应
	 */
	public static String sendGet(String url, String params,Map<String,String> headerMap)
	{
		String result = "";
		BufferedReader in = null;
		try
		{
			String urlName = url + "?" + params;
			URL realUrl = new URL(urlName);
			// 打开和URL之间的连接
			URLConnection conn = realUrl.openConnection();
			if(headerMap!=null&&headerMap.size()>0){
				for(Map.Entry<String,String> entry : headerMap.entrySet()){
					conn.setRequestProperty(entry.getKey(),entry.getValue());
				}
			}
			// 设置通用的请求属性
//			conn.setRequestProperty("accept", "*/*");
//			conn.setRequestProperty("connection", "Keep-Alive");
//			conn.setRequestProperty("user-agent",
//				"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
			// 建立实际的连接
			conn.connect();
//			// 获取所有响应头字段
//			Map<String, List<String>> map = conn.getHeaderFields();
//			// 遍历所有的响应头字段
//			for (String key : map.keySet())
//			{
//				System.out.println(key + "--->" + map.get(key));
//			}
			// 定义BufferedReader输入流来读取URL的响应
			in = new BufferedReader(
				new InputStreamReader(conn.getInputStream()));
			String line;
			StringBuilder sb = new StringBuilder();
			while((line = in.readLine()) != null) {
				sb.append(line);
			}
			result = sb.toString();
			log.debug("返回信息："+result);
		}
		catch (Exception e)
		{
			log.error("发送GET请求出现异常！" + e);
			e.printStackTrace();
		}
		// 使用finally块来关闭输入流
		finally
		{
			try
			{
				if (in != null)
				{
					in.close();
				}
			}
			catch (IOException ex)
			{
				ex.printStackTrace();
			}
		}
		return result;
	}

	/**
	 * 向指定URL发送POST方法的请求
	 * 
	 * @param url
	 *            发送请求的URL
	 * @param params
	 *            请求参数，请求参数应该是name1=value1&name2=value2的形式。
	 * @return URL所代表远程资源的响应
	 */
	public static String sendPost(String url, String params)
	{
		PrintWriter out = null;
		BufferedReader in = null;
		String result = "";
		try
		{
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			URLConnection conn = realUrl.openConnection();
			// 设置通用的请求属性
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent",
				"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
			// 发送POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);
			// 获取URLConnection对象对应的输出流
			out = new PrintWriter(conn.getOutputStream());
			// 发送请求参数
			out.print(params); // params.toString().getBytes("UTF-8");
			// flush输出流的缓冲
			out.flush();
			// 定义BufferedReader输入流来读取URL的响应
			in = new BufferedReader(
				new InputStreamReader(conn.getInputStream()));
			String line;
			StringBuilder sb = new StringBuilder();
			while((line = in.readLine()) != null) {
				sb.append(line);
			}
			result = sb.toString();
			log.debug("返回信息："+result);
		}
		catch (Exception e)
		{
			log.error("发送POST请求出现异常！" + e);
			e.printStackTrace();
		}
		// 使用finally块来关闭输出流、输入流
		finally
		{
			try
			{
				if (out != null)
				{
					out.close();
				}
				if (in != null)
				{
					in.close();
				}
			}
			catch (IOException ex)
			{
				ex.printStackTrace();
			}
		}
		return result;
	}
	
	public static String send(String method, String url, StringBuilder parameter) {
		URL urlObj;
		HttpURLConnection httpConn;
		BufferedReader in = null;
		String result = "";
		try {
			urlObj = new URL(url);
			httpConn = (HttpURLConnection) urlObj.openConnection();
			httpConn.setDoOutput(true);
			httpConn.setDoInput(true);
			httpConn.setRequestMethod(method); // POST/GET

			// 发送请求参数
			httpConn.getOutputStream().write(
					parameter.toString().getBytes("UTF-8"));
			httpConn.getOutputStream().flush();
			httpConn.getOutputStream().close();
			httpConn.getResponseCode();
			// httpConn.getInputStream();// 仅执行但不获取返回内容

			// 定义BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(
					httpConn.getInputStream()));
			String line;
			StringBuilder sb = new StringBuilder();
			while((line = in.readLine()) != null) {
				sb.append(line);
			}
			result = sb.toString();
			log.debug("返回信息："+result);
		} catch (Exception e) {
			e.printStackTrace();
		}
		// 使用finally块来关闭输入流
		finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		return result;
	}
}
